package com.heima.app.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
@Order(-1)
public class TokenFilter implements GlobalFilter{


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 获取请求头中的token
        //2.1 放行到不需要拦截的请求
        String path = request.getURI().getPath();
        log.info("当前请求路径:{}", path);
        if (path.contains("/login/login_auth")) {
            return chain.filter(exchange);
        }
        //2.2 获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //3. 校验token是否有效
        Claims claims = AppJwtUtil.getClaimsBody(token);
        int result = AppJwtUtil.verifyToken(claims);
        //3.1 token无效, 向客户端返回错误信息
        if (result != 0 && result != -1) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //3.2 token有效, 获取token中的userId
        String userId = claims.get("id").toString();
        log.info("获取到当前登录用户id:{}",userId);
        //4. 将userId发送到下游服务中
        //4.1 对请求对象进行重新构建 , 返回新的请求对象
        ServerHttpRequest httpRequest = request
                // 重建 , 重构
                .mutate()
                .headers(httpHeaders -> httpHeaders.add("userId", userId))
                .build();
        //4.2 对交换机进行重新构建, 设置新的请求对象
        ServerWebExchange webExchange = exchange.mutate().request(httpRequest).build();

        return chain.filter(webExchange);

    }
}
